package com.example.software.controller;

import com.example.software.dto.MessageDTO;
import com.example.software.entity.Message;
import com.example.software.service.MessageService;
import com.example.software.vo.ContactVO;
import com.example.software.vo.MessageVO;
import com.example.software.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/messages")
public class MessageController {
    
    private static final Logger log = LoggerFactory.getLogger(MessageController.class);
    
    @Autowired
    private MessageService messageService;
    
    /**
     * 发送消息
     */
    @PostMapping
    public Result<Long> sendMessage(@Valid @RequestBody MessageDTO messageDTO, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        String userType = (String) request.getAttribute("userType");
        log.info("接收到发送消息请求 - 发送者ID: {}, 用户类型: {}, 接收者ID: {}, 任务ID: {}", 
                userId, userType, messageDTO.getReceiverId(), messageDTO.getTaskId());
        
        try {
            // 参数验证
            if (messageDTO.getReceiverId() == null) {
                log.error("消息参数无效 - 接收者ID为空");
                return Result.error("接收者ID不能为空");
            }
            
            if (messageDTO.getTaskId() == null) {
                log.error("消息参数无效 - 任务ID为空");
                return Result.error("任务ID不能为空");
            }
            
            if (messageDTO.getContent() == null || messageDTO.getContent().trim().isEmpty()) {
                log.error("消息参数无效 - 消息内容为空");
                return Result.error("消息内容不能为空");
            }
            
            // 检查用户是否发给自己
            if (messageDTO.getReceiverId().equals(userId)) {
                log.warn("用户尝试给自己发送消息 - 用户ID: {}", userId);
                return Result.error("不能给自己发送消息");
            }
            
            log.debug("消息内容: {}", messageDTO.getContent());
            Long messageId = messageService.sendMessage(messageDTO, userId);
            log.info("消息发送成功 - 消息ID: {}", messageId);
            return Result.success(messageId);
        } catch (Exception e) {
            log.error("发送消息时发生错误", e);
            return Result.error("发送消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取消息列表
     */
    @GetMapping
    public Result<List<Message>> getMessageList(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("获取消息列表 - 用户ID: {}", userId);
        
        try {
            // 获取消息列表
            List<Message> messageList = messageService.getMessageList(userId);
            log.info("获取消息列表成功 - 用户ID: {}, 消息数量: {}", userId, messageList.size());
            return Result.success(messageList);
        } catch (Exception e) {
            log.error("获取消息列表时发生错误", e);
            return Result.error("获取消息列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取联系人列表
     */
    @GetMapping("/contacts")
    public Result<List<ContactVO>> getContactList(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("获取联系人列表 - 用户ID: {}", userId);
        
        try {
            List<ContactVO> contactList = messageService.getContactList(userId);
            return Result.success(contactList);
        } catch (Exception e) {
            log.error("获取联系人列表时发生错误", e);
            return Result.error("获取联系人列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取与特定用户的对话
     */
    @GetMapping("/conversation/{contactId}")
    public Result<List<MessageVO>> getConversation(@PathVariable Long contactId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("获取对话消息 - 用户ID: {}, 联系人ID: {}", userId, contactId);
        
        try {
            List<MessageVO> messages = messageService.getConversation(userId, contactId);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("获取对话消息时发生错误", e);
            return Result.error("获取对话消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 标记消息为已读
     */
    @PostMapping("/{messageId}/read")
    public Result<Boolean> markAsRead(@PathVariable Long messageId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("标记消息为已读 - 用户ID: {}, 消息ID: {}", userId, messageId);
        
        try {
            boolean result = messageService.markAsRead(messageId, userId);
            log.info("标记消息为已读成功 - 消息ID: {}", messageId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("标记消息为已读时发生错误", e);
            return Result.error("标记消息为已读失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread/count")
    public Result<Integer> getUnreadMessageCount(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("获取未读消息数量 - 用户ID: {}", userId);
        
        try {
            int count = messageService.getUnreadMessageCount(userId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取未读消息数量时发生错误", e);
            return Result.error("获取未读消息数量失败: " + e.getMessage());
        }
    }
}